import PropTypes from 'react-router/lib/PropTypes';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import {Button, Form,message, Spin} from 'antd'
const createForm = Form.create;
const FormItem = Form.Item;
import isEmpty from 'lodash/isEmpty'
import Immutable from 'immutable'
const is = Immutable.is;
import * as UnderlingAction from '../actions/underling'
import { WeaErrorPage, WeaTools } from 'ecCom'

import {
  WeaTab,
  WeaTop,
  WeaRightMenu,
} from 'ecCom'

import {WeaTable} from 'comsRedux'
const WeaTableAction = WeaTable.action;
import * as PublicFunc from '../utils/pulic-func';

let _this;
class Underling extends React.Component {
  static contextTypes = {
    router: PropTypes.routerShape
  }
  constructor(props) {
    super(props);
    _this = this;
    const funcs = ['onOperatesClick','jumpToHrmCard'];
    funcs.forEach(f=> this[f] = this[f].bind(this))
  }
  componentDidMount() {
    const {condition, actions} = this.props;
    actions.queryData();
  }
  componentWillReceiveProps(nextProps) {
    const { actions,form } = this.props;
    const keyOld = this.props.location.key;
    const keyNew = nextProps.location.key;
    if(keyOld !== keyNew) {
      actions.saveQuickSearch();
      this.componentDidMount();
    }
  }
  shouldComponentUpdate(nextProps, nextState) {
    return  !is(this.props.title,nextProps.title) ||
            !is(this.props.dataKey, nextProps.dataKey)||
            !is(this.props.account, nextProps.account)||
            !is(this.props.quickSearch, nextProps.quickSearch)||
            !is(this.props.comsWeaTable,nextProps.comsWeaTable);
  }
  componentWillUnmount() {
    const {actions} = this.props;
    actions.saveQuickSearch();
  }
  getTitle() {
    const {title, account} = this.props;
    let res = '';
    if (account.get('username')) {
      res = account.get('username') + title;
    }
    return res;
  }
  render() {
    // console.log('render----------------------------');
    const {actions,dataKey, title,comsWeaTable, quickSearch} = this.props;
    const tablekey = dataKey ? dataKey.split('_')[0] : 'init';
    const tableNow = comsWeaTable.get(tablekey);
    const loadingTable = tableNow.get('loading');
    return (
      <div className='wea-myhrm-underling'>
        <WeaRightMenu datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}>
          <WeaTop
            title={this.getTitle()}
            loading={loadingTable}
            icon={<i className='icon-coms-hrm' />}
            iconBgcolor='#217346'
            buttons={[]}
            buttonSpace={10}
            showDropIcon={true}
            dropMenuDatas={this.getRightMenu()}
            onDropMenuClick={this.onRightMenuClick.bind(this)}
          >
            <div style={{height: '100%'}}>
              <WeaTab
                onlyShowRight={true}
                searchType={['base']}
                searchsBaseValue={quickSearch}
                onSearch={v => {actions.queryData()}}
                onSearchChange={v => {actions.saveQuickSearch(v)}}
              />
              <Spin spinning={loadingTable}>
                <WeaTable sessionkey={dataKey}
                  hasOrder={true}
                  needScroll={true}
                  getColumns={c=>this.reRenderColumns(c)}
                  onOperatesClick={this.onOperatesClick}
                  />
              </Spin>
            </div>)
          </WeaTop>
        </WeaRightMenu>
      </div>
    )
  }
  reRenderColumns(columns){
    columns.forEach(c=>{
        if(c.dataIndex=='lastname'){
            c.render = function(text, record){
                return  <span style={{cursor:'pointer'}} className='wea-hrm-linkstyle' onClick={_this.jumpToHrmCard.bind(null,record.id)}>{record.lastname}</span>
            }
        } else {
          c.render = function(text, record){
              let valueSpan = record[c.dataIndex + "span"] !== undefined ? record[c.dataIndex + "span"] : record[c.dataIndex];
              return <span dangerouslySetInnerHTML={{__html: valueSpan}}></span>
            }
        }
    })
    return columns;
  }
  jumpToHrmCard(hrmId,...rest){
    // this.context.router.push({pathname:'/main/hrm/resource/HrmResourceBase',state:hrmId})
    // this.context.router.push({pathname:'/main/hrm/resource4Formal/HrmResourceBase4Formal',state:hrmId})
    window.open('/spa/hrm/index.html#/main/hrm/resource4Formal/HrmResourceBase4Formal/' + hrmId)
  }
  onOperatesClick=(record,index,operate,flag,argumentString)=>{
      const fn = operate.href ? operate.href.split(':')[1].split('(')[0] : '';
      const id = record.id ? record.id : '';
      PublicFunc[fn](id);
  }
  getRightMenu(){
      const keys = this.getSelectedRowKeys();
      const arr = [{
          icon: <i className='icon-coms-ws'/>,
          content:'搜索'
        }, {
          icon: <i className='icon-coms-task-list'/>,
          content:'显示定制列'
        }
        // ,{
        //     icon: <i className='icon-Right-menu-Batch-sharing'/>,
        //     content:'收藏',
        // },{
        //     icon: <i className='icon-Right-menu-Custom'/>,
        //     content:'帮助'
        // }
      ];
      return arr;
  }
  onRightMenuClick(key){
    const {actions,comsWeaTable} = this.props;
    switch(key){
        case '0':
            this.doSearch();
            break;
        case '1':
            this.definedColumn();
            break;
    }
  }
  getSelectedRowKeys(){
    const {comsWeaTable,dataKey} = this.props;
    const tablekey = dataKey ? dataKey.split('_')[0] : 'init';
    const tableNow = comsWeaTable.get(tablekey);
    return tableNow.get('selectedRowKeys').toJS();
  }
  sendEmessage(){
      const keys = this.getSelectedRowKeys();
      const ids = keys ? keys.join(',') : '';
      PublicFunc.sendEmessage(ids);
  }
  exportExcel(){
      const {actions, dataKey} = this.props;
      dataKey && actions.exportExcel(dataKey);
  }
  doSearch() {
      const {actions} = this.props;
      actions.queryData();
  }
  definedColumn() {
      const {actions, dataKey} = this.props;
      actions.setColSetVisible(dataKey, true);
      actions.tableColSet(dataKey, true);
  }
}
//组件检错机制
class MyErrorHandler extends React.Component {
  render() {
    const hasErrorMsg = this.props.error && this.props.error !== "";
    return(
      <WeaErrorPage msg={ hasErrorMsg ? this.props.error : "对不起，该页面异常，请联系管理员！" } />
    );
  }
}

Underling = WeaTools.tryCatch( React, MyErrorHandler, { error: "" })(Underling);

// 把 state map 到组件的 props 上
const mapStateToProps = state => {
    // console.log('==================================================state',state);
  const {hrmUnderling,comsWeaTable, theme} = state;
  return {
    title:hrmUnderling.get('title'),
    dataKey:hrmUnderling.get('dataKey'),
    quickSearch:hrmUnderling.get('quickSearch'),
    comsWeaTable: comsWeaTable, //绑定整个table
    account: theme.get('account'),
  }
}

// 把 dispatch map 到组件的 props 上
const mapDispatchToProps = dispatch => {
  return {
    actions: bindActionCreators({...UnderlingAction,...WeaTableAction}, dispatch)
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(Underling);